package com.adtech.farmProducts.blue;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.adtech.farmProducts.R;
import com.adtech.farmProducts.blue.adapter.Event;
import com.adtech.farmProducts.blue.adapter.ListViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private BluetoothAdapter mAdapter;
    private Context mContext;
    private boolean isScanning = false;
    private Handler mHandler = new Handler();
    private Button btn_rescan;
    private Button btn_disconnect;
    private TextView tx_display;
    private ListView lv_scan;
    private List<Event> enentList = new ArrayList<>();
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothGatt mBluetoothGatt;
    private TextView tx_receive;
    private EditText et_send;
    private Button bt_send;
    private Button bt_clear;


    private BluetoothGattCharacteristic characteristic;
    private BluetoothGattCharacteristic readCharacteristic;
    BluetoothGattService linkLossService;
    BluetoothGattCharacteristic alertLevel;
    byte[] WriteBytes = new byte[20];


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();//初始化控件
        //initListData();//初始化list数据
        mContext = MainActivity.this;


        if (isBluetoothValid()) { //判断设备是否支持Ble蓝牙

            if (!isBluetoothOpen()) {
                Toast.makeText(this, "请打开蓝牙开关", Toast.LENGTH_SHORT).show();
            }
            if (isBluetoothOpen()) { //蓝牙已经打开，则开始进行蓝牙搜索
                Log.e("onCreate 中中中:", "搜索搜索搜索搜索");
                scanDevice();
            }
        }

        btn_rescan.setOnClickListener(this);
        btn_disconnect.setOnClickListener(this);
        bt_send.setOnClickListener(this);
        bt_clear.setOnClickListener(this);

        lv_scan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Event event1 = eventList.get(position);
                connect(event1.getDevice());
                //Toast.makeText(mContext, event1.toString(), Toast.LENGTH_SHORT).show();
            }
        });


    }

    private void initView() {
        btn_rescan = (Button) findViewById(R.id.btn_rescan_mainactivity);//重新扫描
        btn_disconnect = (Button) findViewById(R.id.btn_disconnect_mainactivity);//断开连接
        tx_display = (TextView) findViewById(R.id.tx_display_mainactivity);
        tx_display.setText("开始扫描 \n");
        lv_scan = (ListView) findViewById(R.id.lv_scan_mainactivity);
        tx_receive = (TextView) findViewById(R.id.tx_receive_inactivity);
        et_send = (EditText) findViewById(R.id.et_send_inactivity);
        bt_send = (Button) findViewById(R.id.bt_send_inactivity);
        bt_clear = (Button) findViewById(R.id.bt_clear_inactivity);

    }

    /**
     * 判断是否支持蓝牙设备
     *
     * @return
     */
    public boolean isBluetoothValid() {
        Log.e("isBluetoothValid 中中中:", "判断是否支持蓝牙设备");
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1 ||
                !mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            return false;
        }
        BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        mAdapter = bluetoothManager.getAdapter();
        if (mAdapter == null) {
            return false;
        }
        return true;
    }

    /**
     * 打开蓝牙
     */
    private void enableBluetooth() {
        if (!mAdapter.isEnabled()) {
            mAdapter.enable();
        }
    }

    /**
     * 判断蓝牙是否打开
     *
     * @return boolean
     */
    private boolean isBluetoothOpen() {
        Log.e("isBluetoothOpen 中中中:", "判断蓝牙是否打开");
        //BluetoothManager bManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        //mAdapter = bManager.getAdapter();
        return mAdapter.isEnabled();
    }


    /**
     * 蓝牙扫描
     */
    public void scanDevice() {
//        Log.e("scanDevice 中中中:", "蓝牙扫描 蓝牙扫描");
//        if(isScanning){
//            return;
//        }
//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                if(!isScanning){
//                    return;
//                }
//                mAdapter.stopLeScan(mLeScanCallback);
//                Log.e("scanDevice 中中中:", "扫描结束 扫描结束"+enentList.toString());
//                ListViewAdapter adapter = new ListViewAdapter(mContext, R.layout.listview, enentList);
//                lv_scan.setAdapter(adapter);
//                isScanning = false;
//            }
//        }, 8000) ;
//
//        mAdapter.startLeScan(mLeScanCallback);
//        isScanning = true;

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // null:表示不支持蓝牙
        Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices(); // 获取已经配对的蓝牙设备
        for (BluetoothDevice bluetoothDevice : bondedDevices) {
//            Event event = new Event(bluetoothDevice.getName(), bluetoothDevice);
//            eventList.add(event);
        }

        ListViewAdapter adapter = new ListViewAdapter(mContext, R.layout.listview, eventList);
        lv_scan.setAdapter(adapter);
    }

    private List<Event> eventList = new ArrayList<>();
    /**
     * 扫描回调mLeScanCallback的实现
     */
    BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device.toString() == "00:15:83:00:6E:31") {
                connect(device);
            }
            Log.e("mLeScanCallback中onLS:", " mLeScanCallback的实现");

            // TODO Auto-generated method stub
            String deviceName = device.getName();
            tx_display.append("扫描到目标设备： " + deviceName + "==" + device.toString() + "\n");
            Log.e("扫：tx_display", deviceName + "==" + device.toString());
        }
    };

    /**
     * 蓝牙连接
     *
     * @param device
     */
    public void connect(BluetoothDevice device) {
     /*   if (null == device || !mBluetoothAdapter.isEnabled()) { //设备为空或者蓝牙未开启，返回
            return;
        }*/
        Log.e("connect中中中", "开始连接:");
        mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
    }

    /**
     * 断开连接
     */
    public void disconnect() {

        if (null == mBluetoothGatt) {
            return;
        }
        mBluetoothGatt.disconnect();
    }

    /**
     * 连接回调，结果处理
     */
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {//连接状态改变

            Log.e("BluetoothGatt中中中", "连接状态:" + newState);
            /**
             * 连接状态：
             *    * The profile is in disconnected state   *public static final int STATE_DISCONNECTED  = 0;
             *    * The profile is in connecting state     *public static final int STATE_CONNECTING    = 1;
             *    * The profile is in connected state      *public static final int STATE_CONNECTED    = 2;
             *    * The profile is in disconnecting state  *public static final int STATE_DISCONNECTING = 3;
             *
             */

            if (BluetoothGatt.STATE_CONNECTED == newState) {
                Log.e("onConnec中中中", "连接成功:");
                gatt.discoverServices();//必须有，可以让onServicesDiscovered显示所有Services
                tx_display.append("连接成功");


                Toast.makeText(mContext, "连接成功", Toast.LENGTH_SHORT).show();
            } else if (BluetoothGatt.STATE_DISCONNECTED == newState) {
                Log.e("断开 中中中", "断开连接:");
                Toast.makeText(mContext, "断开连接", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {//发现服务，在蓝牙连接的时候会调用
            List<BluetoothGattService> list = mBluetoothGatt.getServices();
            for (BluetoothGattService bluetoothGattService : list) {
                String str = bluetoothGattService.getUuid().toString();
                Log.e("onServicesDisc中中中", " ：" + str);
                List<BluetoothGattCharacteristic> gattCharacteristics = bluetoothGattService
                        .getCharacteristics();
                for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                    Log.e("onServicesDisc中中中", " ：" + gattCharacteristic.getUuid());
                    if ("49535343-1e4d-4bd9-ba61-23c647249616".equals(gattCharacteristic.getUuid().toString())) {
                        linkLossService = bluetoothGattService;
                        alertLevel = gattCharacteristic;
                        Log.e("daole", alertLevel.getUuid().toString());
                    }
                }

            }
            enableNotification(true, gatt, alertLevel);//必须要有，否则接收不到数据
            //Log.e("onServicesDisc中中中", " ：" + mBluetoothGatt.getServices().toString());
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic, int status) {
            Log.e("onCharacteristicRead中", "数据接收了哦" + bytesToHexString(characteristic.getValue()));
        }

        /**
         *  发送数据后的回调
         * @param gatt
         * @param characteristic
         * @param status
         */
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic, int status) {//发送数据时调用
            Log.e("onCharacteristicWrite中", "数据发送了哦");
            Log.e("onCharacteristicWrite中", bytesToHexString(characteristic.getValue()));
            if (status == BluetoothGatt.GATT_SUCCESS) {//写入成功
                Log.e("onCharacteristicWrite中", "写入成功");
                tx_display.append("写入成功");
            } else if (status == BluetoothGatt.GATT_FAILURE) {
                Log.e("onCharacteristicWrite中", "写入失败");
            } else if (status == BluetoothGatt.GATT_WRITE_NOT_PERMITTED) {
                Log.e("onCharacteristicWrite中", "没权限");
            }

        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt,
                                     BluetoothGattDescriptor descriptor, int status) {//descriptor读
            Log.e("onCDescripticRead中", "数据接收了哦"+bytesToHexString(characteristic.getValue()));
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {// Characteristic 改变，数据接收会调用
            Log.e("CharacteristicChanged中", "数据接收" + bytesToHexString(characteristic.getValue()));
            tx_receive.append(bytesToHexString(characteristic.getValue()) + "\n");
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                                      BluetoothGattDescriptor descriptor, int status) {//descriptor写
            System.out.println("descriptor写");
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            System.out.println("status");
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { //读Rssi
            System.out.println("status2");
        }

        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {

            System.out.println("status3");
        }

    };

    /**
     * 向蓝牙发送数据
     */
    public void dataSend() {
        //byte[] send={(byte) 0xaa,0x01,0x01,(byte)0x81,(byte) 0xff};
        byte[] send = new byte[20];
        //et_send.getText().toString().getBytes();
        send = hexStringToBytes(et_send.getText().toString());
        byte[] sendData = new byte[send.length + 2];
        sendData[0] = (byte) 0xaa;
        sendData[sendData.length - 1] = (byte) 0xff;
        for (int i = 1; i < sendData.length - 1; i++) {
            sendData[i] = send[i - 1];
        }
        Log.e("dataSend", bytesToHexString(sendData));
        Log.e("dataSend", linkLossService + "");
        alertLevel.setValue(sendData);
        boolean status = mBluetoothGatt.writeCharacteristic(alertLevel);
        Log.e("dataSend", status + "");
    }

    /**
     * @param v button的监听方法
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_rescan_mainactivity:
                //重新扫描,先清空list再扫描
                enentList.clear();
                tx_display.setText("");
                Log.e("onClick", "重新扫描");
                scanDevice();
                break;
            case R.id.btn_disconnect_mainactivity:
                //断开连接
                disconnect();
                break;
            case R.id.bt_send_inactivity:
                //发送数据
                dataSend();

                break;
            case R.id.bt_clear_inactivity:
                //清空接收区和发送区
                tx_receive.setText("");
                et_send.setText("");

                break;
            default:
                break;
        }
    }

    public String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    // HexString byte
    public byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    private void enableNotification(boolean enable, BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        if (gatt == null || characteristic == null)
            return; //这一步必须要有 否则收不到通知 gatt.setCharacteristicNotification(characteristic, enable);
        // BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(UUIDUtils.CCC); if (enable) { clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); } else { clientConfig.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE); } //准备数据 BleWriteData bData = new BleWriteData(); bData.write_type = BleWriteData.DESCRIP_WRITE;//数据种类 bData.object = clientConfig; //将数据加入队列 mWriteQueue.add(bData); }
        //这一步必须要有 否则收不到通知 gatt.setCharacteristicNotification(characteristic, enable); BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(UUIDUtils.CCC); if (enable) { clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); } else { clientConfig.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE); } //准备数据 BleWriteData bData = new BleWriteData(); bData.write_type = BleWriteData.DESCRIP_WRITE;//数据种类 bData.object = clientConfig; //将数据加入队列 mWriteQueue.add(bData);
        gatt.setCharacteristicNotification(characteristic, enable);
    }


}


